#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QPixmap>
#include <QPalette>

loginWindow::loginWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::loginWindow)
{
    ui->setupUi(this);

    // --- 设置界面 ---
    QPixmap pixmap("../../../resource/1.jpg");
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);
    this->setPalette(palette);
    this->setWindowTitle("患者端"); // 窗口标题是患者端

    // --- 初始化网络连接 ---
    clientSocket = new QTcpSocket(this);

    // --- 绑定信号与槽 ---
    connect(clientSocket, &QTcpSocket::connected, this, &loginWindow::onConnected);
    connect(clientSocket, &QTcpSocket::disconnected, this, &loginWindow::onDisconnected);
    connect(clientSocket, &QAbstractSocket::errorOccurred, this, &loginWindow::displayError);
    connect(clientSocket, &QTcpSocket::readyRead, this, &loginWindow::onReadyRead);

    // 禁用登录按钮，直到连接成功
    ui->LoginButton->setEnabled(false);
    // 如果你有状态标签，可以在这里更新
    // ui->statusLabel->setText("正在连接服务器...");

    // --- 异步连接服务器 ---
    qDebug() << "Patient client: Attempting to connect to server...";
    clientSocket->connectToHost("101.43.50.74", 8081);

    // 创建后续窗口的实例
    selectWindowPtr = new SelectWindow(clientSocket);
}

loginWindow::~loginWindow()
{
    delete ui;
}

// --- 网络事件处理 ---

void loginWindow::onConnected()
{
    qDebug() << "Patient client: Connected to server successfully!";
    ui->LoginButton->setEnabled(true);
    // if (ui->statusLabel) ui->statusLabel->setText("已连接到服务器");
}

void loginWindow::onDisconnected()
{
    qDebug() << "Patient client: Disconnected from server.";
    ui->LoginButton->setEnabled(false);
    QMessageBox::warning(this, "连接断开", "与服务器的连接已断开。");
}

void loginWindow::displayError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    QString errorMsg = clientSocket->errorString();
    qDebug() << "Patient client: Connection error:" << errorMsg;
    QMessageBox::critical(this, "网络错误", "无法连接到服务器: " + errorMsg);
}

void loginWindow::onReadyRead()
{
    qDebug() << "Patient client: Data received from server.";
    QByteArray data = clientSocket->readAll();
    QString receivedData = QString::fromUtf8(data).trimmed();

    if (receivedData.isEmpty()) return;

    // 这是一个简化的判断，防止处理其他窗口的数据
    if (!receivedData.contains(ui->UserNameEdit->text()) && receivedData != "failed") {
        qDebug() << "Patient client: Ignoring irrelevant data:" << receivedData;
        return;
    }

    if (receivedData == "failed") {
        QMessageBox::warning(this, "登录失败", "用户名或密码无效。");
    } else {
        QStringList parts = receivedData.split('|');
        if (parts.size() < 3) { // 患者表至少需要 id|name|username
            QMessageBox::critical(this, "解析错误", "服务器响应格式不正确。");
            return;
        }

        bool ok;
        int userId = parts[0].toInt(&ok);
        if (!ok) {
            QMessageBox::critical(this, "解析错误", "无法从服务器响应中解析用户ID。");
            return;
        }

        currentUserID = userId;
        currentUserTrueName = parts[1];
        currentUserName = parts[2];

        qDebug() << "Patient login successful:" << currentUserTrueName << ", username:" << currentUserName << ", id:" << currentUserID;

        // 【关键】登录成功后，断开这个窗口的信号，防止干扰
        disconnect(clientSocket, &QTcpSocket::readyRead, this, &loginWindow::onReadyRead);

        selectWindowPtr->show();
        this->hide();
    }
}

// --- 按钮和窗口管理 ---

void loginWindow::on_LoginButton_clicked()
{
    if (clientSocket->state() != QAbstractSocket::ConnectedState) {
        QMessageBox::warning(this, "提示", "尚未连接到服务器，正在尝试重连...");
        clientSocket->connectToHost("101.43.50.74", 8081);
        return;
    }

    QString username = ui->UserNameEdit->text();
    QString password = ui->PassWordEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "提示", "用户名和密码不能为空！");
        return;
    }

    // 查询的是 Patients 表
    QString queryStr = "SELECT * FROM Patients WHERE username = '" + username + "' AND password = '" + password + "';";
    qDebug() << "Patient client: Sending login query:" << queryStr;
    clientSocket->write(queryStr.toUtf8());
}

void loginWindow::on_createAccountButton_clicked()
{
    if (clientSocket->state() != QAbstractSocket::ConnectedState) {
        QMessageBox::information(this, "提示", "请先等待连接服务器成功后再注册。");
        return;
    }
    createAccountWindowPtr = new CreateAccoutWindow(clientSocket);
    createAccountWindowPtr->show();
    connect(createAccountWindowPtr, &CreateAccoutWindow::back, this, &loginWindow::CreateAccountWindow_closed);
    this->hide();
}

void loginWindow::CreateAccountWindow_closed()
{
    if (createAccountWindowPtr) {
        createAccountWindowPtr->close();
        delete createAccountWindowPtr;
        createAccountWindowPtr = nullptr;
    }
    this->show();
}
